package ${package}.utils;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 *
 * 对象转换类
 *
 * @author ${author}
 * @date ${date}
 */
public class BeanUtil {

    public static <T> T copy(Object source, Class<T> target) {
        if (null == source){
            return null;
        }
        try {
            T to = target.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, to);
            return to;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> List<T> copy(Collection<?> sourceList, Class<T> target) {
        if (sourceList == null || sourceList.isEmpty()) {
            return Collections.emptyList();
        }
        try {
            List<T> outList = new ArrayList<>(sourceList.size());
            for (Object source : sourceList) {
                if (source == null) {
                    continue;
                }
                T to = target.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(source, to);
                outList.add(to);
            }
            return outList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }
}